import { queryCompanies } from '@/pages/SystemUser/service';
import { Role } from '@/utils/typings.d';
import ProForm, {
  ModalForm,
  ProFormDigit,
  ProFormSelect,
  ProFormSlider,
  ProFormSwitch,
  ProFormText,
  ProFormTextArea,
} from '@ant-design/pro-form';
import { message } from 'antd';
import { useModel } from 'umi';
import { queryDingRobotNames, updateSystemWarningRule } from '../../service';
import type { UpdateSystemWarningRule, SystemWarningRuleTableItem } from '../../typings.d';

const UpdateRuleModal = (props: {
  visible: boolean;
  reload: () => void;
  setUnvisible: () => void;
  warningRule: SystemWarningRuleTableItem;
}) => {
  const { initialState } = useModel('@@initialState');
  const userRole = initialState?.currentUser?.role;
  const { visible, setUnvisible, warningRule } = props;
  return (
    <ModalForm<UpdateSystemWarningRule & { phone_target?: string }>
      width={650}
      title="更新通知规则"
      layout="horizontal"
      visible={visible}
      modalProps={{
        destroyOnClose: true,
        onCancel: () => {
          setUnvisible();
        },
      }}
      initialValues={{
        name: warningRule?.name,
        description: warningRule?.description,
        enable: warningRule?.enable,
        effectiveTime: warningRule?.effectiveTime,
        interval: warningRule?.interval,
        ding: warningRule?.ding,
        phone_target: warningRule?.dingTargetPhones?.join(';'),
        appliedUsers: warningRule?.appliedUsers,
        ownerId: warningRule?.ownerId,
      }}
      onFinish={async (values) => {
        const {
          effectiveTime,
          enable,
          interval,
          name,
          phone_target,
          ding,
          description,
          appliedUsers,
          ownerId,
        } = values;
        const data2up: UpdateSystemWarningRule = {
          name,
          effectiveTime,
          interval,
          enable,
          description,
          dingTargetPhones: phone_target?.split(';') || [],
          ding: ding || [],
          appliedUsers: appliedUsers || [],
          ownerId,
        };
        const res = await updateSystemWarningRule(warningRule._id, data2up);
        if (res?.success) {
          message.success({ content: res.message, key: 'update_warning_rule' });
          props?.reload();
          setUnvisible();
          return true;
        }
        message.error({ content: res?.message, key: 'update_warning_rule' });
        return false;
      }}
    >
      <ProFormText
        name="name"
        label="规则名称"
        tooltip="最长为 20 位"
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 20 }}
        placeholder="请输入规则名称"
        rules={[
          {
            required: true,
            validator: async (_, nameVal) => {
              if ((nameVal !== undefined && nameVal.length < 2) || !nameVal || nameVal?.length > 20)
                return Promise.reject(new Error('规则名称长度应满足不少于2个字符，不超过20个字符'));
              return Promise.resolve(nameVal);
            },
          },
        ]}
      />
      <ProForm.Group colProps={{ span: 24 }}>
        <ProFormDigit
          required
          tooltip="(单位: 分钟)"
          colProps={{ span: 12 }}
          label="推送间隔"
          name="interval"
          width="sm"
          initialValue={60}
        />
        <ProFormSwitch
          colProps={{ span: 12 }}
          width="sm"
          label="是否启用"
          name="enable"
          initialValue={false}
        />
      </ProForm.Group>

      <ProFormSelect
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 20 }}
        label="钉钉对象"
        tooltip="如未查找到目标机器人，请前往[通知规则->钉钉机器人]进行新建"
        name="ding"
        placeholder="请选择目标机器人"
        showSearch
        mode="multiple"
        request={(val) => queryDingRobotNames(val.keyWords)}
      />
      <ProFormSlider
        label="生效时段"
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 20 }}
        required
        tooltip="如拖块重合, 默认全天候生效"
        initialValue={[9, 18]}
        name="effectiveTime"
        max={23}
        range={true}
        min={0}
        marks={{
          0: '0点',
          6: '6点',
          9: '9点',
          12: '12点',
          15: '15点',
          18: '18点',
          21: '21点',
          23: '23点',
        }}
      />
      <ProFormText
        label="目标手机"
        name="phone_target"
        tooltip="钉钉通知时需要@的用户的手机号"
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 20 }}
        rules={[
          {
            validator: (rule, val) => {
              const reg = /^\s*(1\d{10}\s*;\s*)*(1\d{10}\s*;?)\s*$/g;
              return new Promise((resolve, reject) => {
                if (val === undefined || val === '' || reg.test(val)) {
                  resolve(val);
                } else {
                  reject(new Error('格式错误，请输入以 ;(英文分号标点) 分隔的手机号'));
                }
              });
            },
          },
        ]}
      />
      <ProFormSelect
        name="appliedUsers"
        label="适用用户"
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 20 }}
        showSearch
        mode="multiple"
        debounceTime={300}
        placeholder="请选择需要使用当前通知规则的用户"
        request={(val) => queryCompanies(val.keyWord, true)}
      />
      <ProFormTextArea
        label="规则描述"
        name="description"
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 20 }}
      />
      {userRole === Role.ADMIN && (
        <ProFormSelect
          name="ownerId"
          label="用户归属公司"
          showSearch
          debounceTime={200}
          rules={[{ required: true, message: '请选择用户目标公司' }]}
          placeholder="请选择用户归属公司(如未找到目标公司，请优先创建[企业管理者])"
          request={(val) => queryCompanies(val.keyWords, true)}
        />
      )}
    </ModalForm>
  );
};

export default UpdateRuleModal;
